<template>
  <div class="anime-management">
    <!-- 操作工具栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon> 新增动漫
      </el-button>

      <el-button
          type="danger"
          :disabled="!selectedAnimes.length"
          @click="handleBatchDelete">
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>

      <div class="search-group">
        <el-input
            v-model="searchQuery"
            placeholder="搜索动漫名称"
            clearable
            style="width: 240px"
            @keyup.enter="fetchData"
        />
        <el-button type="primary" @click="fetchData">
          <el-icon><Search /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="filteredAnimes"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="videoCover" label="封面" width="120">
        <template #default="{ row }">
          <CoverImg
              :src="row.videoCover"
              fit="cover"
              style="width: 80px; height: 120px"
              :preview-src-list="[row.videoCover]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" sortable />
      <el-table-column prop="genre" label="类型" width="240">
        <template #default="{ row }">
          <el-tag
              v-for="tag in row.tags"
              :key="tag"
              style="margin-right: 5px"
          >
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="rating" label="评分" sortable width="160">
        <template #default="{ row }">
          <el-rate v-model="row.rating" disabled />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="作品状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 2 ? 'warning' : 'success'" v-if="row.status != 0">
          {{ row.status === 2 ? '完结' : '连载中' }}
          </el-tag>
          <el-tag :type="row.status === 0 ? 'info' : 'success'" v-else>
            待上映
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="reviewStatus" label="发布状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.reviewStatus === 1 ? 'success':'warning'" v-if="row.reviewStatus != 0">
            {{ row.reviewStatus === 1 ? '发布' : '驳回' }}
          </el-tag>
          <el-tag :type="row.reviewStatus === 0 ? 'info' : 'success'" v-else>
            待审核
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="50%"
    >
      <anime-form
          ref="formRef"
          :initial-data="dialog.data"
          @submit="handleSubmit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import AnimeForm from '../components/AnimeFrom.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {deleteVideoInfo, loadDataList} from "@/api/video.js";
import CoverImg from "@/components/CoverImg.vue";

// 数据状态
const loading = ref(false)
const searchQuery = ref('')
const selectedAnimes = ref([])
const formRef = ref(null)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗配置
const dialog = reactive({
  visible: false,
  title: '',
  data: {
    title: '',
    rating: null,
    videoCover: '',
    releaseDate: '',
    episode: 0,
    tags: [],
    introduction: '',
    publisher: '',
    mainCharacters: [{ name: '', cv: '' }],
    staff: {
      originalAuthor: '',
      director: '',
      seriesComposer: '',
      characterDesigner: '',
      music: '',
      reviewStatus:'',
    },
    region: '中国',
    status: 0,
    reviewStatus: 0,
  }
})

// 数据
const animeList = ref([])

// 计算属性
const filteredAnimes = computed(() => {
  return animeList.value.filter(item =>
      item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 加载数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await loadDataList(pagination.pageSize,pagination.currentPage,searchQuery.value)
    animeList.value = res.data.list.map(item => ({
      ...item,
      rating: item.rating / 2,
      tags:JSON.parse(item.tags),
      mainCharacters: JSON.parse(item.mainCharacters),
      staff:JSON.parse(item.staff)
    }))

    pagination.total = res.data.totalCount
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection) => {
  selectedAnimes.value = selection
}

const handleCreate = () => {
  dialog.title = '新增动漫'
  dialog.data = {
    title: '',
    rating: null,
    videoCover: '',
    videoChartCover: '',
    releaseDate: '',
    episode: 0,
    tags: [],
    introduction: '',
    publisher: '',
    mainCharacters: [{ name: '', cv: '' }],
    staff: {
      originalAuthor: '',
      director: '',
      seriesComposer: '',
      characterDesigner: '',
      music: '',
      reviewStatus:'',
    },
    region: '中国',
    status: 0,
    reviewStatus: 0,
  }
  dialog.visible = true
}

const handleEdit = (row) => {
  dialog.title = '编辑动漫'
  dialog.data = {...row}
  dialog.visible = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除动漫《${row.title}》吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteVideoInfo(row.videoId)
    ElMessage.success('删除成功')
    fetchData()
  })
}

const handleBatchDelete = () => {
  if (!selectedAnimes.value.length) return

  ElMessageBox.confirm(`确定删除选中的${selectedAnimes.value.length}部动漫吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedAnimes.value.map(async item =>
        await deleteVideoInfo(item.videoId)
    )
    ElMessage.success(`已删除${ids.length}部动漫`)
    fetchData()
  })
}

const handleSubmit = () => {
  dialog.visible = false
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.anime-management {
  padding: 20px;
}

.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.search-group {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
<style>
.el-dialog{
  margin-top: 4%;
}
</style>
